<template>
  <div class="video-box">
    <div v-if="!data" class="no-video video-desc-box">
      <i class="el-icon-video-camera"></i>
    </div>
    <template v-else>
      <div v-if="videoOffline" class="video-offline video-desc-box">
        <el-image :src="videoOfflineIcon"></el-image>
        <div class="text">视频离线</div>
      </div>
      <div class="video-main-box" v-if="videoOnline">
        <VideoTimeline
          ref="videoTimeline"
          :videoData="data"
          :isPlaying="isPlaying"
          :canPlayBack="canPlayBack"
          :videoCurrentTime="videoCurrentTime"
          :isHuiYan="isHuiYan"
          @updateVideoUrl="updateVideoUrl"
          @seedVideo="handleSeedVideo"
          @seedError="handleSeedError"
          @updateUrlBefore="handleUpdateUrlBefore"
          @isPlayBackUrl="updateIsPlayBackUrl"
          @scalePlusTime="scalePlusTime"
          @scalePlay="handleScalePlay"
        >
          <div class="video-main">
            <div class="video-desc-box" v-if="errorExceed">
              <div class="text-center">
                <div>该视频暂时无法查看,请查看切换视频</div>
                <br>
                <i @click="reTryVideo" class="el-icon-video-play"></i>
              </div>
            </div>
            <div class="video" ref="video"></div>
            <div class="video-info" v-if="showVideoInfo">
              <div class="left">
                {{ playUrlDesc }} {{ data.machineName }}
              </div>
              <div class="right">
                <el-image
                  class="status-img"
                  v-if="statusIcon"
                  :src="statusIcon"
                  fit="contain"
                ></el-image>
                {{ statusText }}
                <i
                  v-if="showCloseIcon"
                  @click="handleCloseVideo"
                  class="el-icon-close icon"
                ></i>
              </div>
            </div>
            <VideoControl ref="videoControl"
              v-if="videoControl_show"
              @toggle-playing="togglePlaying"
              @full-screen="setFullScreen"></VideoControl>
          </div>
        </VideoTimeline>
      </div>
    </template>
  </div>
</template>

<script>
// machinePlatform : 1 普通平台 2 慧眼
// 如果视频没显示 请设置父级高度
// 如果视频没显示 请设置父级高度
// 如果视频没显示 请设置父级高度

// 视频-正常
import videoNormalIcon from "@/assets/icon_camera_online.png";
// 视频-离线
import videoOfflineIcon from "@/assets/icon_camera_offline.png";
// 视频-报警
import videoAlarmIcon from "@/assets/icon_camera_alarm.png";

// import 'xgplayer';
// import FlvPlayer from 'xgplayer-flv';
// import FlvJsPlayer from 'xgplayer-flv.js';  
// import { getVideoBackControl, getVideoBackUrl, getVideoUrl } from '@/api/subSystem/basicInfo' 
// import { videoBaseUrl } from '@/config';
import {buildCameraPlay} from '@/api/build/camera.js'

import VideoTimeline from '@/components/video-timeline'
import VideoControl from './videoControl.vue'

const iconEnum = {
  1: {
    icon: videoNormalIcon,
    text: "在线",
  },
  2: {
    icon: videoOfflineIcon,
    text: "离线",
  },
};
const videoStatusEnum = {
  online: {
    status: "1",
    text: "在线",
  },
  offline: {
    status: "2",
    text: "离线",
  },
};

export default {
  name: "v-video",
  components: {
    VideoControl,
    VideoTimeline
  },
  props: {
    videoIndex: {
      type: Number,
      default: 0
    },
    showVideoInfo: {
      type: Boolean,
      default: false,
    },
    canPlayBack: {
      type: Boolean,
      default: false,
    },
    showCloseIcon: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default() {
        return {};
      },
    },
    playerConf: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      value: [],
      videoOfflineIcon,
      player: null,
      isPlayBackUrl: false,
      isUserPause: false,
      isPlaying: false,
      errorTimes: 0,
      seedTime: 0,
      lastTime: 0,
      playedTime: 0,
      scaleTime: 0,
      videoCurrentTime: 0,
      videoControl_show: true,
    }
  },
  computed: {
    isHuiYan() {
      return String(this.data.machinePlatform) === '2'
    },
    playUrlDesc() {
      if (this.isPlayBackUrl) {
        return '正在回放:'
      } else {
        return '正在直播:'
      }
    },
    videoOnline() {
      if (!this.data) {
        return false;
      }
      const { machineOnline = videoStatusEnum.offline.status } = this.data;
      return String(machineOnline) !== videoStatusEnum.offline.status;
    },
    videoOffline() {
      if (!this.data) {
        return false;
      }
      const { machineOnline = videoStatusEnum.offline.status } = this.data;
      return String(machineOnline) === videoStatusEnum.offline.status;
    },
    statusText() {
      if (!this.data) {
        return "";
      }
      const { machineOnline = videoStatusEnum.offline.status } = this.data;
      return iconEnum[machineOnline].text;
    },
    statusIcon() {
      if (!this.data) {
        return "";
      }
      const { machineOnline = videoStatusEnum.offline.status } = this.data;
      return iconEnum[machineOnline].icon;
    },
    errorExceed() {
      return this.errorTimes >= 1
    }
  },
  watch: {
    data: {
      async handler(newVal, oldVal) {
        if (!newVal) {
          return false
        }
        this.errorTimes = 0
        await this.$nextTick()
        this.getNewVideoUrl(newVal)
      },
      immediate: true
    }
  },
  mounted() {
    // console.log('如果视频没显示 请设置父级高度');
  },
  methods: {
    async reTryVideo() {
      await this.destroyVideo()
      this.errorTimes = 0
      this.initVideo()
    },
    togglePlaying(isPlaying) {
      console.log('isPlayBackUrl', this.isPlayBackUrl)
      if (isPlaying) {
        this.player.play()
      } else {
        this.isUserPause = true
        this.player.pause()
      }
    },
    setFullScreen() {
      this.player.setFullscreen(true)
    },
    async updateVideoUrl(url) {
      if (url) {
        this.data.url = url
      }
      this.resetTimes()
      this.initVideo()
    },
    async getVideoUrl(data = this.data) {
      console.log('getVideoUrl====',data)
      if (String(data.machineOnline) !== videoStatusEnum.online.status) {
        this.destroyVideo()
        return false
      }
      if (!this.isHuiYan) {
        await new Promise((resolve) => {
          setTimeout(() => {
            resolve()
          }, this.videoIndex * 4000)
        })
      }
      const urlRes = await buildCameraPlay({
        // machineNum: data.machineNum,
        // id: data.id
        deviceId: data.machineCode
      })
      if (urlRes.code === 200) {
        // const url = urlRes.data.playUrl
        // const url = urlRes.data.wsFlv
        const url = urlRes.data.playUrl
        // console.log('url', url)
        this.data.url = url
      } else {
        this.destroyVideo()
      }
    },
    async getNewVideoUrl(data = this.data) {  
      await this.getVideoUrl(data)
      this.updateVideoUrl()
    },
    async initVideo(data = this.data) {
      console.log('data===initVideo',data,'this==',this)
      await this.destroyVideo()
      await this.$nextTick()
      if (!this.player) {
        //判断是flv还是m3u8
        const isFlv = data.url.indexOf('.flv') > -1
        const isM3u8 = data.url.indexOf('.m3u8') > -1
        if(isM3u8){
          this.videoControl_show = false
          // M3u8用xgp播放器
          this.player = new HlsJsPlayer({
            el: this.$refs.video,
            "id": "mse",
            url: data.url,
            autoplay: true,
            autoplayMuted: true,
            cors: true,
            screenShot: true,
            isLive: true,
            fluid: true,
            ignores: ['volume'],
            height: 500,
            // ...this.playerConf,
          });
        }else if(isFlv){
          this.videoControl_show = true
          // flv用Jessibuca
          this.player = new Jessibuca({ 
            container: this.$refs.video,
            videoBuffer: 0.5, // 缓存时长
            isResize: false,
            text: '',
            // isFlv: true,
            supportDblclickFullscreen: true,
            loadingText: '加载中',
            // 是否开启当页面的'visibilityState'变为'hidden'的时候，自动暂停播放。
            hiddenAutoPause: false,
            hasAudio: false,
            debug: false,
            isFullResize: true,
            showBandwidth: false, // 显示网速
            heartTimeoutReplay: true,
            operateBtns: {
              fullscreen: false,
              audio: false
            },
            forceNoOffscreen: true,
            isNotMute: false
          }).on('error', (e) => {
            console.log('error', e)
            this.errorTimes++
            this.isPlaying = false
            if (this.$refs.videoControl) {
              this.$refs.videoControl.setPlaying(false)
            }
          }).on('play', () => {
            this.isPlaying = true
            if (this.$refs.videoControl) {
              this.$refs.videoControl.setPlaying(true)
            }
          }).on('pause', () => {
            this.isPlaying = false
            if (this.$refs.videoControl) {
              this.$refs.videoControl.setPlaying(false)
            }
            this.isUserPause = false
          }).on('timeUpdate', (time) => {
            if (time - this.lastTime > 1000) {
              this.lastTime = time
              this.videoCurrentTime = time + this.seedTime - this.playedTime + this.scaleTime
            }
          })
          this.player.play(data.url)
        }
      }
      // console.log('data.url', data.url)
    },
    resetTimes() {
      this.videoCurrentTime = 0
      this.playedTime = 0
      this.seedTime = 0
      this.lastTime = 0
      this.scaleTime = 0
      this.data.isScalePlay = false
    },
    handleUpdateUrlBefore() {
      this.resetTimes()
      this.isUserPause = true
      this.player.pause()
    },
    updateIsPlayBackUrl(isPlayBackUrl) {
      this.isPlayBackUrl = isPlayBackUrl
    },
    handleScalePlay() {
      this.data.isScalePlay = true
    },
    scalePlusTime() {
      this.scaleTime += 1000
    },
    handleCloseVideo() {
      this.$emit("close-video", this.data)
      this.destroyVideo()
    },
    handleSeedVideo(range) {
      if (this.isPlayBackUrl) {
        this.playedTime = this.lastTime
      }
      this.lastTime = 0
      this.seedTime = range * 1000
    },
    handleSeedError() {
      this.seedTime = 0
    },
    destroyVideo() {
      if (this.$refs.videoControl) {
        this.$refs.videoControl.setPlaying(false)
      }
      return new Promise((resolve) => {
        this.player && this.player.destroy()
        setTimeout(() => {
          this.player = null
          delete this.player
          resolve()
        })
      })
    }
  },
  async beforeDestroy() {
    await this.destroyVideo()
  }
}
</script>

<style lang="scss" scoped>
.video-box {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  &:hover {
    .video-main-box{
      ::v-deep .video-main {
        .video-info {
          .right {
            .icon {
              opacity: 1;
            }
          }
        }
      }
    }
  }

  .video-desc-box {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #000000;
    font-size: 16px;
    z-index: 999;
    color: #fff;
    i {
      font-size: 58px;
      color: #fff;
    }
    .text {
      margin-left: 10px;
    }
  }
  // .video-offline{

  // }
  // .no-video {
  // }
  .video-main-box{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    flex-grow: 1;
    ::v-deep .video-main {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-direction: column;
      position: relative;
      .video {
        max-width: 100%;
        max-height: 100%;
        background-color: #000;
      }
      .video-info {
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        height: 38px;
        line-height: 38px;
        padding: 0 19px;
        font-size: 14px;
        color: #fff;
        cursor: default;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        background-color: rgba(0, 0, 0, 0.6);
        z-index: 999;
        // .left{
        // }
        .right {
          height: 38px;
          line-height: 38px;
          display: flex;
          align-items: center;
          margin-left: 15px;
          .status-img {
            width: 13px;
            height: 15px;
            margin-right: 7px;
          }
          .icon {
            transition: all 0.3s;
            opacity: 0;
            cursor: pointer;
            font-size: 24px;
            padding: 5px;
          }
        }
      }
      ::v-deep {
        .xgplayer-screenshot {
          .name {
            span {
              display: none;
            }
            &:after {
              content: "抓拍";
              width: fit-content;
              padding: 0 10px;
              height: 20px;
              line-height: 20px;
              background: rgba(0, 0, 0, 0.38);
              border-radius: 10px;
            }
          }
        }
      }
      .video-progress{
        position: absolute;
        left: 0;
        bottom: 0;
        right: 0;
      }
    }
    ::v-deep .video-time-slider-box{
      bottom: 120px;
    }

  }
}
</style>
